package com.lottery.ruok.lottrey.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.NavigateBar;
import utils.LogUtil;
import utils.Utils;

public class WebViewActivity extends BaseActivity {
    public static final String EXTRAL_TITLE = "EXTRAL_TITLE";
    public static final String EXTRAL_URL = "url";

    private static final String BRIDGE_NAME = "android_js";

    @BindView(R.id.webview)
    WebView mWebView;
    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    private String mCurrentUrl;
    private String title;
    private WebViewJavascriptBridge mJsbridge;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.activity_discounts);
        ButterKnife.bind(this);

        initView();
    }

    private void initData() {
        mCurrentUrl = getIntent().getStringExtra(EXTRAL_URL);
        title = getIntent().getStringExtra(EXTRAL_TITLE);

    }

    private void initView() {
        try {
            mWebView.getSettings().setJavaScriptEnabled(true);

            mWebView.setWebViewClient(new InnerWebViewClient());
            mWebView.setWebChromeClient(new InnerWebChromeClient());
            mWebView.requestFocus();
            mWebView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });

            mJsbridge = new WebViewJavascriptBridge(WebViewActivity.this, mWebView);
            loadUrl(mCurrentUrl);
        } catch (Exception e) {
            e.printStackTrace();//https://blog.csdn.net/u014021258/article/details/78253164
        }

    }


    public void loadUrl(String url) {
        if (mWebView != null) {
            mWebView.loadUrl(url);
        }
    }


    class WebViewJavascriptBridge {

        @SuppressLint("JavascriptInterface")
        public WebViewJavascriptBridge(Activity activity, WebView mWebView) {
            mWebView.addJavascriptInterface(this, BRIDGE_NAME);
        }

        @JavascriptInterface
        public void goLogin() {
            if (Utils.isEmpty(UserInfo.getToken())) {
                gotoLoginActivity();
            }
        }
    }

    public class InnerWebChromeClient extends WebChromeClient {


        /**
         * 开启Html5地理位置定位
         */
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            //加载完成度的百分数
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            LogUtil.i("[onJsAlert] : " + message);
            if (result == null) {
                return true;
            }
            result.confirm();
            Toast.makeText(view.getContext(), message, Toast.LENGTH_LONG).show();
            return true;
        }

        /**
         * 拦截js 的 prompt方法
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String value, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, value, result);
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            LogUtil.i("[onJsBeforeUnload] url:" + url + " message:" + message);
            return super.onJsBeforeUnload(view, url, message, result);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            LogUtil.i("[onReceivedTitle] title:" + title);
            if (Utils.isEmpty(WebViewActivity.this.title)) {
                navigateBar.setCenterTitle(title);
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            LogUtil.i("[onConsoleMessage] console:" + consoleMessage.message());
            return super.onConsoleMessage(consoleMessage);
        }
    }

    private class InnerWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            LogUtil.i("shouldOverrideKeyEvent ");
            return super.shouldOverrideKeyEvent(view, event);
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            super.onUnhandledKeyEvent(view, event);
            LogUtil.i("onUnhandledInputEvent ");
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtil.i("onPageStarted ");
//            showLoading();
//            checkUserAgent(view);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url) {
            LogUtil.i("shouldOverrideUrlLoading url : " + url);
            if (url.equals(mCurrentUrl)) {
                refresh();
                return true;
            }
            loadUrl(url);

            return super.shouldOverrideUrlLoading(webview, url);
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    /**
     * 后退
     */
    public boolean backward() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }

    /**
     * 前进
     */
    public boolean forward() {
        if (mWebView.canGoForward()) {
            mWebView.goForward();
            return true;
        }
        return false;
    }

    /**
     * 刷新
     */
    public void refresh() {
        loadUrl(mCurrentUrl);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            backward();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    public static void startActivity(Activity activity, String title, String url) {
        if (Utils.isEmpty(url)) {
            url = UserInfo.getQuickDomain() + "slideshow";
        }
        Intent intent = new Intent(activity, WebViewActivity.class);
        intent.putExtra(EXTRAL_TITLE, title);
        intent.putExtra(EXTRAL_URL, url);
        activity.startActivity(intent);
    }
}
